package tushare

import (
	"fmt"
	"log"
	"os"
	"time"

	"net/http"

	"strings"
	"tushare/model"

	"github.com/PuerkitoBio/goquery"
)

var intChan chan string

func ImStock() {
	stocks := model.StockList()
	for _, v := range stocks {
		time.Sleep(1 * time.Second)
		go readStock(v.TsCode)
	}
}

func readStock(tsCode string) {
	tsCodeArr := strings.Split(tsCode, ".")
	if tsCodeArr[1] == "SH" || tsCodeArr[1] == "SZ" {
		url := "https://xueqiu.com/S/" + tsCodeArr[1] + tsCodeArr[0]
		h := &http.Client{Timeout: 30 * time.Second}
		res, err := h.Get(url)
		if err != nil {
			fmt.Println(err)
		}

		if res.StatusCode != 200 {

		}

		doc, err := goquery.NewDocumentFromReader(res.Body)

		if err != nil {
			fmt.Println(err)
		}

		doc.Find(".stock-current").Each(func(i int, s *goquery.Selection) {
			text := s.Find("strong").Text()
			price := strings.TrimLeft(text, "¥")

			logFile, logErr := os.OpenFile("E:/gitee/golang/tushare/cmd/test.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
			if logErr != nil {
				fmt.Println("Fail to find", *logFile, "cServer start Failed")
				os.Exit(1)
			}
			log.SetOutput(logFile)
			log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

			//write log
			log.Printf("%s %s\n", tsCode, price)
		})
	}

}
